package com.heima.article.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DownOrUpListener {

    @Autowired
    private ArticleConfigMapper articleConfigMapper;

    /*
    监听文章上下架功能
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_QUEUE, durable = "true",
                            arguments = {
                                    @Argument(name = "x-dead-letter-exchange", value = "error.down.direct"),
                                    @Argument(name = "x-dead-letter-routing-key", value = "error.down")
                            }),
                    exchange = @Exchange(name = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, type = ExchangeTypes.TOPIC),
                    key = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY
            )
    )
    public void getMessage(WmNews wmNews) {
        //文章消费者见听到的消息，对文章进行上下架
        log.info("文章消费者收到消息：{}", wmNews);
        //将消息转换成对象
        //进行健壮性判断
        if (wmNews == null || wmNews.getId() == null) {
            log.error("未接收到消息");
        }
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setId(Long.valueOf(wmNews.getId()));
        if (wmNews.getEnable().equals(WmNews.Status.SUBMIT.getCode())) {
            apArticleConfig.setIsDown(true);
        } else {
            apArticleConfig.setIsDown(false);
        }
//        if (true){
//            log.error("222文章配置保存失败");
//            throw new RuntimeException("222文章配置保存失败") ;
//        }
        //修改配置
        int i = articleConfigMapper.update(apArticleConfig, Wrappers.<ApArticleConfig>lambdaUpdate()
                .eq(ApArticleConfig::getArticleId, wmNews.getArticleId()));
        if (i <= 0) {
            throw new RuntimeException("文章配置保存失败");
        }
        log.info("文章配置保存成功");
        log.info("文章消费者结束");
    }
}
